import React from 'react';
import { hashHistory } from 'react-router';
import { setCommonDate } from '../action/Action';
import * as DataName from "../action/DataNameConfig";
import { Select } from 'antd';
import {Tool} from './Tool';
import * as api from "./Api";
const Util = {};
const Option = Select.Option;

/* 验证是否为空 */
Util.IsNull = function (obj) {
    var flag = false;
    if (obj === null || obj === undefined || typeof (obj) === 'undefined' || obj === '') {
        flag = true;
    } else if (typeof (obj) === 'string') {
        obj = obj.trim();
        if (obj === '') {//为空
            flag = true;
        } else {//不为空
            obj = obj.toUpperCase();
            if (obj === 'NULL' || obj === 'UNDEFINED' || obj === '{}') {
                flag = true;
            }
        }
    }
    else {
        flag = false;
    }
    return flag;
}


Util.Trim = function(str,is_global){
    var result;
    result = str.replace(/(^\s+)|(\s+$)/g,"");
    if(is_global.toLowerCase()==="g"){
        result = result.replace(/\s/g,"");
    }
    return result;
}

Util.loginOut = function(){
    Tool.removeLocalItem('company');
    Tool.removeLocalItem('User');
    Tool.removeLocalItem('fieldType');
    Tool.removeLocalItem('tagList');
    Tool.removeLocalItem("domainArray");
    Tool.removeLocalItem("count");
}

/*
 * 验证是否为手机号
 * */
Util.Phone= function (obj) {
    if(Util.IsNull(obj)){
        return false;
    }
    if(!(/^1(3|4|5|7|8)\d{9}$/.test(obj))){
        return false;
    }
    return true;
}
/**
 * type：api分类
 * key: api标识
 */
Util.getApi = (type,key)=> {
    let obj=null;
    var apiObj = api[type];
    for(let i=0,len=apiObj.length;i<len;i++){
        if(apiObj[i].key===key){
            obj=apiObj[i];
            return obj;
        }
    }
};


Util.initChangeSelect=(obj)=>{
    var strArr = [];
    if(obj && obj.length>0){
        obj.map(d=>{
            return strArr.push(d.issueId);
        })
    }
    return strArr;
}

Util.IsNullJson=(rowData)=>{
    if(JSON.stringify(rowData) === "{}"){
        return true;
    }else{
        return false;
    }
}


Util.isLogin=(type,old)=>{
    //实时判断是否登录状态
    var token = JSON.parse(Tool.localItem("User")) ? JSON.parse(Tool.localItem("User")).token : '';
    var flag=true;
    if(!(token && token.length>0)){//为空，去登录
        if(type === 1){
            return false;
        }else{
            hashHistory.push("/login");
            return false;
        }
    }
    return flag;
}

Util.ComUserLogin=()=>{
    var nowUrl = window.location.href;
    if(!Util.isLogin(1,0)){
        if(!(nowUrl.indexOf("/login")>-1)){
            hashHistory.push("/login");
        }
    }
}

Util.paginationInit=(list)=>{
    var pagination = {
        defaultCurrent:1,current:1,
        total:0,pageSize:10,
        showSizeChanger:true
    }
    if(list && list.content && list.content.length>0){
        pagination.total = list.totalElements;
        pagination.pageSize = list.size;
        pagination.current = list.number+1;
    }
    return pagination;
}

Util.toString=(val,def)=>{
    if(Util.IsNull(val)){
       return def?def:"——";
    }
    return val;
}

Util.getYear=(startYear,type)=>{
    var now = 2017;var yearOption = [];
    if(type===0){
        yearOption.push(<Option value={""} key="0">开始时间</Option>);
    }else{
        yearOption.push(<Option value={""} key="0">结束时间</Option>);
    }
    if(startYear<1){
        return yearOption;
    }
    for(var i=now;i>startYear-1;i--){
        yearOption.push(<Option value={i+""} key={i}>{i}</Option>);
    }
    return yearOption;
}

Util.initPrivate=(obj)=>{
    var arr = [];
    if(obj && obj.length > 0){
        obj.map(item =>arr.push(item.id))
    }
    return arr;
}
/* 判断是否有权限操作 */
Util.hasPermission=(id)=>{
    var arr = Tool.getSession("userPrivate") || [];
    var flag = false;
    if(arr && arr.length > 0){
        arr.map(it=> (it === id)?flag = true:"")
    }
    return flag;
}

Util.resetWindowTitle=(obj,typ)=>{
    let title = "监督系统",icon = "/favicon.ico";
    if(obj && obj.saasOrg){
        if(obj.saasOrg.dept_name){
            title = obj.saasOrg.dept_name + (typ === 0?"":" | 监督系统");
        }
        if(obj.saasOrg.avatar){
            icon = obj.saasOrg.avatar;
        }
    }
    var objsLink = document.getElementsByTagName("link");
    if(objsLink && objsLink.length>0){
        for(var i=0;i<objsLink.length;i++){
            if(objsLink[i].rel.indexOf("shortcut icon")>-1){
                document.head.removeChild(objsLink[i]);
            }
        }
    }
    document.title=title;
    var link = document.createElement("link");
    link.href = icon;
    link.rel = "shortcut icon";
    document.head.appendChild(link);
}

/* 数据展示 */
Util.getStrByObjArr =(obj,index,typeStr)=>{
    var reStr = "";
    if(obj && obj.length>index){
        reStr = obj[index][typeStr]
    }
    return reStr;
}

Util.getIsObligedByObjArr =(obj,index)=>{
    var reStr = false;
    if(obj && obj.length>index){
        reStr = (obj[index].isHide === 0 && obj[index].isObliged) === 1?true:false
    }
    return reStr;
}

Util.TransferString=(content)=>{
    var string = content;
    try{
        string=string.replace(/\r\n/g,"<br/>")
        string=string.replace(/\n/g,"<br/>");
    }catch(e) {
        console.log(e.message);
    }
    return string;
}
Util.TransferStringInput=(content)=>{
    var string = content;
    try{
        string=string.replace(/<br\/>/g,"\n")
    }catch(e) {
        console.log(e.message);
    }
    return string;
}
Util.createMarkup=(val)=>{
    return {__html: val};
}

Util.setMenuOpenKey = function (props,type) {
    let { dispatch } = props;
    dispatch(setCommonDate("set_base_data",DataName.MENU_OPEN_KEY,(DataName.MENUS_KEYS[type] || "")))
}

Util.formateDateObj=(obj)=>{
    if(!obj) return;
    return obj.year+"-"+((obj.monthValue<10?"0":"")+obj.monthValue)+"-"
        +((obj.dayOfMonth<10 && "0") + obj.dayOfMonth)+" "
        +((obj.hour<10 && "0")+obj.hour)+":"
        +((obj.minute<10 && "0")+obj.minute)+":"
        +((obj.second<10 && "0")+obj.second);
}


export default Util;
